package com.tomdd.task;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 定时任务执行类
 *
 * @author zx
 * @date 2025年04月18日 14:07
 */
@Data
@Slf4j
@Component
@PropertySource("classpath:/task-time-init.properties")
public class ScheduleTask implements SchedulingConfigurer {
    @Value("${printTime.cron}")
    private String cron;

    /**
     * 默认循环间隔时间为10s
     */
    private long timer = 10000L;
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //动态使用cron表达式设置循环间隔
        taskRegistrar.addTriggerTask(() -> {
            log.info("Current Time:{}", LocalDateTime.now());
        }, triggerContext -> {
            //使用不同的触发器，为设置循环时间的关键，区别于CronTrigger触发器，
            // 该触发器可随意设置循环间隔时间，单位为毫秒
            PeriodicTrigger periodicTrigger = new PeriodicTrigger(Duration.ofMillis(timer));
            return periodicTrigger.nextExecution(triggerContext);


            //使用CronTrigger触发器,可动态修改cron表达式来操作循环规则
            //CronTrigger cronTrigger = new CronTrigger(cron);
            //return cronTrigger.nextExecution(triggerContext);
        });
    }
}
